package com.example.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket服务类
 * 提供WebSocket消息发送和会话管理功能
 */
@Slf4j
@Service
public class WebSocketService {

    @Autowired
    private ObjectMapper objectMapper;

    // 存储用户ID和WebSocket会话的映射
    private final Map<String, WebSocketSession> userSessions = new ConcurrentHashMap<>();

    /**
     * 添加用户会话
     */
    public void addSession(String userId, WebSocketSession session) {
        userSessions.put(userId, session);
        log.info("添加WebSocket会话: userId={}, sessionId={}", userId, session.getId());
    }

    /**
     * 移除用户会话
     */
    public void removeSession(String userId) {
        WebSocketSession session = userSessions.remove(userId);
        if (session != null) {
            log.info("移除WebSocket会话: userId={}, sessionId={}", userId, session.getId());
        }
    }

    /**
     * 发送消息给指定用户
     */
    public boolean sendMessageToUser(String userId, Object message) {
        WebSocketSession session = userSessions.get(userId);
        if (session != null && session.isOpen()) {
            try {
                String jsonMessage = objectMapper.writeValueAsString(message);
                session.sendMessage(new TextMessage(jsonMessage));
                log.debug("发送WebSocket消息成功: userId={}, message={}", userId, jsonMessage);
                return true;
            } catch (IOException e) {
                log.error("发送WebSocket消息失败: userId={}, error={}", userId, e.getMessage(), e);
                // 如果发送失败，移除无效会话
                userSessions.remove(userId);
            }
        } else {
            log.warn("用户会话不存在或已关闭: userId={}", userId);
        }
        return false;
    }

    /**
     * 广播消息给所有在线用户
     */
    public void broadcastMessage(Object message) {
        String jsonMessage;
        try {
            jsonMessage = objectMapper.writeValueAsString(message);
        } catch (Exception e) {
            log.error("序列化广播消息失败: {}", e.getMessage(), e);
            return;
        }

        userSessions.entrySet().removeIf(entry -> {
            String userId = entry.getKey();
            WebSocketSession session = entry.getValue();
            
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(jsonMessage));
                    return false; // 保留会话
                } catch (IOException e) {
                    log.error("广播消息失败: userId={}, error={}", userId, e.getMessage());
                    return true; // 移除无效会话
                }
            } else {
                log.debug("移除已关闭的会话: userId={}", userId);
                return true; // 移除已关闭的会话
            }
        });

        log.info("广播消息完成: 当前在线用户数={}", userSessions.size());
    }

    /**
     * 发送通知消息
     */
    public void sendNotification(String userId, String title, String content, String type) {
        Map<String, Object> notification = Map.of(
            "type", "notification",
            "title", title,
            "content", content,
            "notificationType", type,
            "timestamp", System.currentTimeMillis()
        );
        sendMessageToUser(userId, notification);
    }

    /**
     * 发送订单状态更新通知
     */
    public void sendOrderStatusUpdate(String userId, Long orderId, String status, String message) {
        Map<String, Object> orderUpdate = Map.of(
            "type", "orderUpdate",
            "orderId", orderId,
            "status", status,
            "message", message,
            "timestamp", System.currentTimeMillis()
        );
        sendMessageToUser(userId, orderUpdate);
    }

    /**
     * 发送聊天消息
     */
    public void sendChatMessage(String fromUserId, String toUserId, String content, String messageType) {
        Map<String, Object> chatMessage = Map.of(
            "type", "chat",
            "fromUserId", fromUserId,
            "toUserId", toUserId,
            "content", content,
            "messageType", messageType,
            "timestamp", System.currentTimeMillis()
        );
        sendMessageToUser(toUserId, chatMessage);
    }

    /**
     * 发送公告消息
     */
    public void sendAnnouncement(String title, String content, String targetType) {
        Map<String, Object> announcement = Map.of(
            "type", "announcement",
            "title", title,
            "content", content,
            "targetType", targetType,
            "timestamp", System.currentTimeMillis()
        );
        
        if ("all".equals(targetType)) {
            broadcastMessage(announcement);
        } else {
            // 根据targetType发送给特定用户群体
            // 这里可以根据业务需求实现更复杂的逻辑
            broadcastMessage(announcement);
        }
    }

    /**
     * 获取在线用户数量
     */
    public int getOnlineUserCount() {
        return userSessions.size();
    }

    /**
     * 检查用户是否在线
     */
    public boolean isUserOnline(String userId) {
        WebSocketSession session = userSessions.get(userId);
        return session != null && session.isOpen();
    }

    /**
     * 获取所有在线用户ID
     */
    public java.util.Set<String> getOnlineUserIds() {
        return userSessions.keySet();
    }
}
